'use client';

import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Pagination from '@/components/Pagination';
import styles from './page.module.css';
import { useRouter } from 'next/navigation';
import { useSession } from 'next-auth/react';
import { Toaster, toast } from 'react-hot-toast'; // 引入toast提示

const CommentAdmin = () => {
    const router = useRouter();
    const { data: session, status, update } = useSession(); // 获取会话信息
    const [comments, setComments] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [currentPage, setCurrentPage] = useState(1);
    const [commentsPerPage] = useState(10);
    const [searchTerm, setSearchTerm] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [selectedComments, setSelectedComments] = useState([]);
    const [isAdmin, setIsAdmin] = useState(false); // 标记是否为管理员

    // 计算总页数
    const totalPages = Math.ceil(comments.length / commentsPerPage);

    // 获取当前页的评论
    const indexOfLastComment = currentPage * commentsPerPage;
    const indexOfFirstComment = indexOfLastComment - commentsPerPage;
    const currentComments = comments.slice(indexOfFirstComment, indexOfLastComment);

    // 权限验证逻辑（带 session 刷新）
    // CommentAdmin 组件中的权限验证
    useEffect(() => {
        if (status === 'loading') return;

        if (status === 'unauthenticated') {
            toast.error('请先登录');
            router.push('/dashboard/login?redirect=/dashboard/comment-admin');
            return;
        }

        // 字段名从 type 改为 userType
        if (!session?.user?.userType) {
            console.log("userType 缺失，刷新 session...");
            update({ trigger: 'sync' });
            return;
        }

        // 判断条件改为 userType === 'admin'
        if (session.user.userType !== 'admin') {
            toast.error('权限不足，仅管理员可访问');
            router.push('/dashboard/login?redirect=/dashboard/comment-admin');
            return;
        }

        setIsAdmin(true);
    }, [status, session, router, update]);
    // 加载评论数据（仅管理员可加载）
    useEffect(() => {
        // 非管理员不加载数据
        if (!isAdmin) return;

        const fetchComments = async () => {
            try {
                setLoading(true);
                const response = await axios.get('/api/comment', {
                    params: {
                        search: searchTerm,
                        status: statusFilter
                    }
                });

                if (response.data.success && Array.isArray(response.data.data)) {
                    setComments(response.data.data);
                    setError(null);
                } else {
                    throw new Error(response.data.message || '获取评论格式错误');
                }
            } catch (err) {
                setError(err.message || '获取评论失败');
                toast.error(err.message || '获取评论失败');
            } finally {
                setLoading(false);
            }
        };

        fetchComments();
    }, [searchTerm, statusFilter, isAdmin]); // 依赖isAdmin，确保权限验证后再加载

    // 处理单条删除
    const handleDeleteComment = async (commentId) => {
        if (!confirm('确定要删除这条评论吗？')) return;

        try {
            const response = await axios.delete(`/api/comment/${commentId}`);
            if (response.data.success) {
                setComments(prev => prev.filter(comment => comment._id !== commentId));
                setSelectedComments(prev => prev.filter(id => id !== commentId));
                toast.success('删除成功');
            } else {
                throw new Error(response.data.message || '删除失败');
            }
        } catch (err) {
            toast.error(err.message || '删除失败');
        }
    };

    // 批量删除选中评论
    const handleDeleteSelected = async () => {
        if (selectedComments.length === 0) return;
        if (!confirm(`确定要删除选中的 ${selectedComments.length} 条评论吗？`)) return;

        try {
            await Promise.all(
                selectedComments.map(id => axios.delete(`/api/comment/${id}`))
            );
            setComments(prev => prev.filter(comment => !selectedComments.includes(comment._id)));
            setSelectedComments([]);
            toast.success(`已删除选中的 ${selectedComments.length} 条评论`);
        } catch (err) {
            toast.error(err.message || '批量删除失败');
        }
    };

    // 切换评论选中状态
    const handleSelectComment = (commentId) => {
        setSelectedComments(prev =>
            prev.includes(commentId)
                ? prev.filter(id => id !== commentId)
                : [...prev, commentId]
        );
    };

    // 全选/取消全选
    const handleSelectAll = () => {
        if (selectedComments.length === currentComments.length && currentComments.length > 0) {
            setSelectedComments([]);
        } else {
            setSelectedComments(currentComments.map(comment => comment._id));
        }
    };

    // 加载中状态
    if (status === 'loading') {
        return (
            <div className={styles.loadingState}>
                <div className={styles.loadingSpinner}></div>
                <p className={styles.loadingText}>验证权限中...</p>
            </div>
        );
    }

    // 非管理员不渲染页面内容
    if (!isAdmin) {
        return null;
    }

    return (
        <div className={styles.container}>
            <Toaster position="top-right" /> {/* Toast提示容器 */}

            {/* 页面标题 */}
            <div className={styles.titleSection}>
                <p className={styles.subtitle}>管理网站上的所有用户留言</p>
            </div>

            {/* 搜索栏 */}
            <div className={styles.searchBar}>
                <div className={styles.searchInputContainer}>
                    <span className={styles.searchIcon}>🔍</span>
                    <input
                        type="text"
                        placeholder="搜索评论内容、姓名或邮箱..."
                        value={searchTerm}
                        onChange={(e) => setSearchTerm(e.target.value)}
                        className={styles.searchInput}
                    />
                </div>

                <select
                    value={statusFilter}
                    onChange={(e) => setStatusFilter(e.target.value)}
                    className={styles.filterSelect}
                >
                    <option value="all">所有状态</option>
                    <option value="pending">待审核</option>
                    <option value="approved">已通过</option>
                    <option value="rejected">已拒绝</option>
                </select>

                <button
                    onClick={handleDeleteSelected}
                    disabled={selectedComments.length === 0}
                    className={styles.deleteSelectedBtn}
                >
                    🗑️ 删除选中 ({selectedComments.length})
                </button>
            </div>

            {/* 评论列表 */}
            <div className={styles.commentListContainer}>
                {loading && (
                    <div className={styles.loadingState}>
                        <div className={styles.loadingSpinner}></div>
                        <p className={styles.loadingText}>加载评论中...</p>
                    </div>
                )}

                {error && (
                    <div className={styles.errorState}>
                        <div className={styles.errorBox}>
                            <strong>错误:</strong> {error}
                        </div>
                        <button
                            onClick={() => window.location.reload()}
                            className={styles.retryBtn}
                        >
                            重试
                        </button>
                    </div>
                )}

                {!loading && comments.length === 0 && (
                    <div className={styles.emptyState}>
                        <div className={styles.emptyIcon}>💬</div>
                        <p className={styles.emptyText}>暂无评论</p>
                    </div>
                )}

                {!loading && comments.length > 0 && (
                    <table className={styles.commentTable}>
                        <thead>
                            <tr className={styles.tableHeader}>
                                <th>
                                    <input
                                        type="checkbox"
                                        checked={selectedComments.length === currentComments.length && currentComments.length > 0}
                                        onChange={handleSelectAll}
                                        className={styles.checkbox}
                                    />
                                </th>
                                <th>评论内容</th>
                                <th>用户信息</th>
                                <th>状态</th>
                                <th>日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {currentComments.map(comment => (
                                <tr key={comment._id} className={styles.tableRow}>
                                    <td>
                                        <input
                                            type="checkbox"
                                            checked={selectedComments.includes(comment._id)}
                                            onChange={() => handleSelectComment(comment._id)}
                                            className={styles.checkbox}
                                        />
                                    </td>
                                    <td className={styles.commentContent} title={comment.content}>
                                        {comment.content.length > 50 ? `${comment.content.substring(0, 50)}...` : comment.content}
                                    </td>
                                    <td>
                                        <div>{comment.name}</div>
                                        <div className="text-sm text-gray-500">{comment.email}</div>
                                    </td>
                                    <td>
                                        <span
                                            className={`${styles.statusBadge} ${comment.status === 'pending' ? styles.statusPending :
                                                comment.status === 'approved' ? styles.statusApproved :
                                                    styles.statusRejected
                                                }`}
                                        >
                                            {comment.status === 'pending' ? '待审核' :
                                                comment.status === 'approved' ? '已通过' : '已拒绝'}
                                        </span>
                                    </td>
                                    <td>{new Date(comment.createdAt).toLocaleString()}</td>
                                    <td>
                                        <div className={styles.actionGroup}>
                                            <button
                                                onClick={() => router.push(`/dashboard/comment-admin/${comment._id}`)}
                                                className={styles.actionBtn + ' ' + styles.viewBtn}
                                            >
                                                查看详情
                                            </button>
                                            <button
                                                onClick={() => handleDeleteComment(comment._id)}
                                                className={styles.actionBtn + ' ' + styles.deleteBtn}
                                            >
                                                删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            ))}
                        </tbody>
                    </table>
                )}
            </div>

            {/* 分页控件 */}
            {!loading && comments.length > 0 && (
                <Pagination
                    totalPages={totalPages}
                    currentPage={currentPage}
                    onPageChange={setCurrentPage}
                    totalItems={comments.length}
                    itemsPerPage={commentsPerPage}
                />
            )}
        </div>
    );
};

export default CommentAdmin;